#ifndef LINEARLIST_H
#define LINEARLIST_H
#include <stdio.h>
#include <iostream>
using namespace std;
class ListClass
{
    int *List;      //指向线性表的指针
    unsigned nMax;  //表的最大长度
    unsigned nElem; //表中当前的元素个数
    void reSize(int newSize);

public:
    void Init(int n = 10)
    {
        List = new int(n);
        nMax = n;
        nElem = 0;
    };              //初始化针表，最大长度的缺省值为10
    void Elem(int); //在线性表尾增加一个元素
    int &Elem(unsigned n)
    {
        int a = int(n);
        if (a > 0 && a <= nMax)
            return List[a-1];
        else
        {
            cerr << "out  of index" << endl;
            exit(1);
        }
    };                                    //返回线性表中第n个元素的引用
    unsigned Elem(void) { return nElem; } //返回当前线性表中元素的个数
    unsigned Max(void) { return nMax; }   //返回线性表的长度（占用空间数）
    void Print(void) const 
    {
        for (int i = 0; i < nElem; i++)
        {
            cout << "#" << i+1 << ":" << List[i] << endl;
        }
    } //输出线性表中所有的元素
    int GetElem(int i)
    {

        if (i > 0 && i <= nMax)
            return List[i-1];
        else
        {
            cerr << "out  of index" << endl;
            exit(1);
        }
    }; //返回线性表中第i个元素的值
    void Destroy(void)

    {
        delete[] List;
        List = NULL;
    }; //收回线性表占用的存储空间
    friend void operator>>(istream &stm, ListClass& list)
    {
        int a;
        cout << "请输入数量"<<endl;
        stm>>a;
        while((a+list.Elem())>list.nMax)
        {
            cerr<< "超出范围,正在扩容"<<endl;
            list.reSize(2*list.nMax);
        }
        cout << "请开始输入"<<endl;
        for (int c=0;c<a;c++)
        {
            int tem;
        stm>>tem;
        list.Elem(tem);
        }
    }
    friend void operator<<(ostream &stem,const ListClass& list) 
    {
        if(list.nElem)
        {
            for (int i =0;i<list.nElem;i++)
            {
               stem <<"#"<<i+1<<":"<<list.List[i] <<'\t';
            }
        }
    }
};

void ListClass::reSize(int newSize)
{
    int *newList = new int(newSize);
    if (newSize > nMax)
    {

        for (int i = 0; i < nElem; i++)
        {
            newList[i] = List[i];
        }
        delete[] List;
        List = newList;
    }
    else if (newSize < nMax)
    {
        for (int i = 0; i < newSize; i++)
        {
            if (i >= nElem)
                break;
            newList[i] = List[i];
        }
    }
    nMax = newSize;
}
void ListClass::Elem(int n)
{
    if (nElem + 1 > nMax)
    {
        reSize(2 * nMax);
    }
    List[nElem] = n;
    nElem++;
}

#endif